#pragma once
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <string>
#include <functional>
#include <vector>
#include <thread>
#include <mutex>
#include <errno.h>
#include <cerrno>
namespace kp
{
    class threaddata
    {
    public:
        threaddata(std::string &name, int &tickets, pthread_mutex_t &mutex)
            : _name(name), _tickets(tickets), _total(0), _mutex(mutex)
        {
        }
        ~threaddata()
        {
        }

    public:
        std::string _name;
        int &_tickets;
        int _total;
        pthread_mutex_t _mutex;
    };

    class LookGuard
    {
    public:
        LookGuard(pthread_mutex_t *mutex)
            : _mutex(mutex)
        {
            pthread_mutex_lock(_mutex);
        }
        ~LookGuard()
        {
            pthread_mutex_unlock(_mutex);
        }

    private:
        pthread_mutex_t *_mutex;
    };

    template <class T>
    using func_t = std::function<void(T &)>;


    template <typename T>
    class Thread
    {
    public:
        void Excute()
        {
            _func(_data);
        }

    public:
        Thread(func_t<T> func, T &data, const std::string &name = "none-name")
            : _func(func), _data(data), _threadname(name), _stop(true)
        {
        }
        static void *threadroutine(void *args) // 类成员函数，形参是有this指针的！！
        {
            Thread<T> *self = static_cast<Thread<T> *>(args);
            self->Excute();
            return nullptr;
        }
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadroutine, this);
            if (!n)
            {
                _stop = false;
                return true;
            }
            else
            {
                return false;
            }
        }
        void Detach()
        {
            if (!_stop)
            {
                pthread_detach(_tid);
            }
        }
        void Join()
        {
            if (!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }
        std::string name()
        {
            return _threadname;
        }
        void Stop()
        {
            _stop = true;
        }
        ~Thread() {}

    private:
        pthread_t _tid;
        std::string _threadname;
        T &_data; // 为了让所有的线程访问同一个全局变量
        func_t<T> _func;
        bool _stop;
    };

}
